package com.sto.stoapp.widget;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.bluetooth.BluetoothAdapter;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnKeyListener;
import android.content.DialogInterface.OnShowListener;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;

import com.sto.stoapp.StoApplication;
import com.sto.stoapp.activity.R;
import com.sto.stoapp.activity.aviation.jipaoqi.JipaoqiDataEntity;
import com.sto.stoapp.adapter.RecordInfoMenuAdapter;
import com.sto.stoapp.adapter.RecordInfoMenuAdapter.OnDelListener;
import com.sto.stoapp.dataprocess.parcelable.GetTableParcel;
import com.sto.stoapp.dataprocess.parcelable.SelectTableParcel;
import com.sto.stoapp.db.StoDataBaseOperation;
import com.sto.stoapp.db.StoFilePreference;
import com.sto.stoapp.db.constant.RegionInfoConstant;
import com.sto.stoapp.db.constant.StoSalesConstant;
import com.sto.stoapp.db.constant.StoSiteCodeConstant;
import com.sto.stoapp.db.manager.SelectTableManager;
import com.sto.stoapp.db.manager.SqlSelectTableManager;
import com.sto.stoapp.entity.ScanRecordInfoEntity;
import com.sto.stoapp.log.ExceptionLog;
import com.sto.stoapp.manager.SoundManager;
import com.sto.stoapp.scan.ScanRuleManager;
import com.sto.stoapp.status.EnumTableNames;
import com.sto.stoapp.thread.BaseThread;
import com.sto.stoapp.thread.BlueReadThread;
import com.sto.stoapp.util.Helper;
import com.sto.stoapp.widget.StoHhmEditText.EditScanListener;

import java.util.ArrayList;
import java.util.List;

import sto.android.app.StoPdaKeyEvent;

public abstract class StoListenerActivity extends StoScanActivity implements
		StoSalesConstant, StoSiteCodeConstant {

	private TextView scanStatus;
	// private int maxcount = 0;

	private List<ScanRecordInfoEntity> list = new ArrayList<ScanRecordInfoEntity>();
	private ListView recordList;
	List<String> codes = new ArrayList<String>();
	private int listMaxCount = 20;
	private ScanRecordInfoEntity inquiryEntity;
	private RecordInfoMenuAdapter menuAdapter;
	public StoHhmEditText code;
	private static final int DELETE_STATE = 1;
	private String str;
	DelCodeThread delThread;

	protected boolean CONTINUATION_SCAN = true;

	public int CARID_LENGTH = 6;

	public int CAR_CODE_LENGTH = 9;

	public int ROUTE_MIN_LENGTH = 7;

	public int ROUTE_MAX_LENGTH = 11;
	AlertDialog dialog;
	boolean canShowDelDialog = true;
	EnumTableNames mEnumTableNames;
    protected boolean IS_SECURITY_SCAN = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

	}

	private Handler  handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case DELETE_STATE:
				if (delThread != null) {
					delThread.cancelDialog();
					String msgcode = (String) msg.obj;
					if (msg.arg1 == 0) {// 失败
						Helper.showToast(StoListenerActivity.this,
								"删除失败,不存在或者已上传");
					} else if (msg.arg1 == 1) {// 成功

						removeItem(msgcode, msg.arg2);
						if (menuAdapter != null)
							menuAdapter.notifyDataSetChanged();
						editText.setText("");
						Helper.showToast(StoListenerActivity.this, "删除成功");
					}

				}
				showDelDialog();
				break;

			default:
				break;
			}
		}

	};
	Runnable runnable = new Runnable() {

		@Override
		public void run() {
			if (str == null)
				return;
			str = barcodeTrim(str);
			if (isShowDelDialog()) {
				setCodeToDelDialog(str);
				return;
			}
			handlerScanData(str);

		}
	};

	private String barcodeTrim(String barcode) {
		// if (TextUtils.isEmpty(barcode)) {
		// return "";
		// }
		int start = 0, last = barcode.length() - 1;
		int end = last;
		while ((start <= end)
				&& (barcode.charAt(start) <= ' ' || barcode.charAt(start) > '~')) {
			start++;
		}
		while ((end >= start)
				&& (barcode.charAt(end) <= ' ' || barcode.charAt(end) > '~')) {
			end--;
		}
		return barcode.substring(start, end + 1);
	}

	public void initPointLayout(boolean isRecordList) {
		try {
			scanStatus = (TextView) this.findViewById(R.id.scan_status);
			if (recordList == null && isRecordList) {
				recordList = (ListView) findViewById(R.id.record_info_list);

				recordList.setOnItemClickListener(new OnItemClickListener() {

					@Override
					public void onItemClick(AdapterView<?> parent, View view,
							int position, long id) {
						// TODO Auto-generated method stub
						ListView v = (ListView) parent;
						if (v.getSelectedView() != null) {
							final int maxItem = list.size();
							int s = list.size() - position - 1;
							menuAdapter.showRecordInfo(list.get(s)
									.getRecordCode(), maxItem, position);

							// menuAdapter.deleteEvent(maxItem,
							// position,
							// list.get(list.size() - position
							// -1).getRecordCode());

						}
					}

				});
			}

		} catch (Exception e) {
			e.printStackTrace();
			ExceptionLog.writeLog("initPointLayout", e.getMessage());
		}
	}

	/**
	 * 监听按键事件
	 */
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		try {
			keyCode= StoApplication.getStoJni().getEventFuction(keyCode);
			if (event.getAction() == KeyEvent.ACTION_DOWN
					&& event.getRepeatCount() == 0) {
				switch (keyCode) {
				case StoPdaKeyEvent.KEYCODE_SCAN:
					Log.i("onKeyDown", "onKeyDown");
					ScanOpen();
					break;
				case StoPdaKeyEvent.KEYCODE_DEL:
					ScanOff();
					break;
				default:
					break;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			ExceptionLog.writeLog("onKeyDown", e.getMessage());
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	public boolean onKeyUp(int keyCode, KeyEvent event) {
		try {
			if (event.getAction() == KeyEvent.ACTION_UP) {
				keyCode= StoApplication.getStoJni().getEventFuction(keyCode);
				switch (keyCode) {
				case StoPdaKeyEvent.KEYCODE_DEL:
					ScanOff();
					break;
				case StoPdaKeyEvent.KEYCODE_3:// F3 快速删除单号
					// if (canShowDelDialog && getUploadTable() != null
					// && !isShowDelDialog())
					// showDelDialog();
					break;
				default:
					break;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			ExceptionLog.writeLog("onKeyUp", e.getMessage());
		}
		return super.onKeyUp(keyCode, event);
	}

	StoHhmEditText editText;

	protected void showDelDialog() {
		AlertDialog.Builder builder = new Builder(this);

		builder.setTitle("扫描或输入要删除的单号");
		editText = new StoHhmEditText(this);
		builder.setView(editText);
		builder.setNegativeButton("确定", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {

				String mCode = editText.getText().toString();
				if (mCode == null || "".equals(mCode.trim())) {
					Helper.showToast(StoListenerActivity.this, "输入为空");
				} else {
					delThread = new DelCodeThread(StoListenerActivity.this,
							mCode);
					delThread.start();
				}

			}
		});
		builder.setPositiveButton("取消", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();

			}
		});
		dialog = builder.create();

		dialog.setOnKeyListener(new OnKeyListener() {

			@Override
			public boolean onKey(DialogInterface dialog, int keyCode,
					KeyEvent event) {
				onKeyDown(keyCode, event);
				onKeyUp(keyCode, event);
				return false;
			}
		});
		dialog.setOnShowListener(new OnShowListener() {

			@Override
			public void onShow(DialogInterface dialog) {
				ScanOpen();

			}
		});

		dialog.show();
	}

	@SuppressLint("NewApi")
	protected void securityProcess(String code) {
		if(code.isEmpty()){
			return;
		}
		if(getSecurityPackageInfo()&& IS_SECURITY_SCAN) {
			CONTINUATION_SCAN = false;
			Intent intent = new Intent(Intent.ACTION_MAIN);
			intent.addCategory(Intent.CATEGORY_LAUNCHER);
			ComponentName comp = new ComponentName("kaicom.com.security", "kaicom.com.security.MainActivity");
			intent.setComponent(comp);
			intent.putExtra("barcode", code);
			intent.putExtra("com", "申通");
			intent.putExtra("longitude", "");
			intent.putExtra("latitude", "");
			intent.putExtra("netcode", StoFilePreference.getInstance(this).getSiteCode());
			intent.putExtra("workid", StoFilePreference.getInstance(this).getUserCode());
			intent.putExtra("machineid", StoFilePreference.getInstance(this).getMachineCode());

			startActivity(intent);
		}

	}

	/**
	 * 快速删除功能提示框是否 showing
	 * 
	 * @return
	 */
	protected boolean isShowDelDialog() {
		if (dialog != null) {
			return dialog.isShowing();
		}
		return false;
	}

	/**
	 * 将扫描到的单号显示到删除提示框中
	 * 
	 * @param code
	 */
	protected void setCodeToDelDialog(String code) {
		if (editText == null)
			return;
		SoundManager.getInstance(this).playSuccessSound();

		editText.setText(code);
		editText.setSelection(code.length());
	}

	class DelCodeThread extends BaseThread {
		private String codeStr;
		private Context context;

		public DelCodeThread(Context context, String codeStr) {
			super(context);
			this.codeStr = codeStr;
			this.context = context;
			showDialog();
		}

		@Override
		public void run() {
			// TODO Auto-generated method stub
			super.run();
			boolean isDelOk = false;
			StoDataBaseOperation mgr = StoDataBaseOperation
					.getInstance(context);
			int i = 0;

			for (EnumTableNames table : getUploadTable()) {
				if (mgr.deleteScanData(table.ordinal(), codeStr) > 0) {
					isDelOk = true;
					i++;
				}
			}
			Message msg = handler.obtainMessage();
			msg.what = DELETE_STATE;
			if (isDelOk) {
				msg.arg1 = 1;// 删除成功
			} else {
				msg.arg1 = 0; // 删除失败
			}
			msg.arg2 = i;
			msg.obj = codeStr;
			handler.sendMessage(msg);
		}

	}

	public void ScanOpen() {
		boolean scanStatus = scanStatus();
		Log.d("ScanOpen", "" + scanStatus);
		if (!scanStatus) {
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			ScanTipsStatus();
			startScan();
		}
	}

	public void ScanOff() {
		if (scanStatus()) {
			ResumeScanStatus();
			endScan();
		}
	}

	public void ScanTipsStatus() {
		try {
			// scanStatus.setText(R.string.startscan);
		} catch (Exception e) {
			e.printStackTrace();
			ExceptionLog.writeLog("ScanTipsStatus", e.getMessage());
		}
	}

	public void ResumeScanStatus() {
		try {
			scanStatus.setText("");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void initScanRecordAdapter(EnumTableNames TABLE_STATUS) {
		try {
			mEnumTableNames = TABLE_STATUS;
			menuAdapter = new RecordInfoMenuAdapter(this, list, TABLE_STATUS,false);
			menuAdapter.setOnDelListener(new OnDelListener() {

				public void DelListener(String code) {

					if (codes.contains(code))
						codes.remove(code);
				}
			});
			recordList.setAdapter(menuAdapter);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	public void initScanRecordAdapter(EnumTableNames TABLE_STATUS,
									  boolean needJipaoQi) {
		try {
			mEnumTableNames = TABLE_STATUS;
			menuAdapter = new RecordInfoMenuAdapter(this, list, TABLE_STATUS,
					needJipaoQi);
			menuAdapter.setOnDelListener(new OnDelListener() {

				public void DelListener(String code) {

					if (codes.contains(code))
						codes.remove(code);
				}
			});
			recordList.setAdapter(menuAdapter);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	public void addScanRecordInfo(String code) {
		try {
			menuAdapter.counterAdd();
			if (list.size() == listMaxCount) {
				codes.remove(0);
				list.remove(0);
			}
			inquiryEntity = new ScanRecordInfoEntity();
			inquiryEntity.setRecordCode(code);
			inquiryEntity.setImageId(R.drawable.cancel);
			// inquiryEntity.setRecordNumber(String.valueOf(maxcount));
			list.add(inquiryEntity);
			codes.add(code);
			menuAdapter.notifyDataSetChanged();
		} catch (Exception e) {
			e.printStackTrace();
			ExceptionLog.writeLog("addScanRecordInfo", e.getMessage());
		}

	}

	public void addScanRecordInfo(String code, String weight) {
		try {
			if (list.size() == listMaxCount) {
				list.remove(0);
				codes.remove(0);
			}
			menuAdapter.counterAdd();
			inquiryEntity = new ScanRecordInfoEntity();
			inquiryEntity.setRecordCode(code);
			inquiryEntity.setImageId(R.drawable.cancel);
			inquiryEntity.setWeight(weight);

			list.add(inquiryEntity);
			codes.add(code);
			menuAdapter.notifyDataSetChanged();
		} catch (Exception e) {
			e.printStackTrace();
			ExceptionLog.writeLog("addScanRecordInfo", e.getMessage());
		}

	}
	public void addScanRecordInfo(String code, JipaoqiDataEntity jipaoqi) {
		try {
			if (list.size() == listMaxCount) {
				list.remove(0);
				codes.remove(0);
			}
			menuAdapter.counterAdd();
			inquiryEntity = new ScanRecordInfoEntity();
			inquiryEntity.setRecordCode(code);
			inquiryEntity.setImageId(R.drawable.cancel);
			inquiryEntity.setWeight(jipaoqi.weight);
			inquiryEntity.setLenght(jipaoqi.lenght+"");
			inquiryEntity.setWide(jipaoqi.wide+"");
			inquiryEntity.setHight(jipaoqi.high+"");
			inquiryEntity.setVolume(jipaoqi.volume+"");
			list.add(inquiryEntity);
			codes.add(code);
			menuAdapter.notifyDataSetChanged();
		} catch (Exception e) {
			e.printStackTrace();
			ExceptionLog.writeLog("addScanRecordInfo", e.getMessage());
		}

	}
	protected int getListCount() {
		return list.size();
	}

	protected int getIndexOfList(String code) {

		return codes.indexOf(code);
	}

	protected void removeItem(String code, int count) {
		int index = getIndexOfList(code);
		if (index != -1) {
			list.remove(index);
			codes.remove(code);
			if (menuAdapter != null)
				menuAdapter.counterDel();
		}
		deleteCodeNumber(count);

	}

	public void initScanListener() {

		int outTime=StoFilePreference.getInstance(this).getScanHeaderTime();
		if(outTime>0){
			StoApplication.getStoJni().SetScannerTimerOut(outTime);
		}

		if (code != null) {
			code.setEditScanListener(new EditScanListener() {

				@Override
				public void onScan() {
					ScanOpen();
				}

				@Override
				public void offScan() {
					ScanOff();
				}
			});
		}
	}

	@Override
	public void showNotice() {

		if(null == menuAdapter){
			finish();
			return;
		}


		if (menuAdapter.getCount() > 0) {
			setSaveData(true);
		} else {
			setSaveData(false);
		}
		super.showNotice();
	}

	@Override
	public void onBackPressed() {
		endScan();
		finish();
	}

	protected RecordInfoMenuAdapter getAdapter() {
		return menuAdapter;
	}

	protected ListView getListView() {
		return recordList;
	}

	public BluetoothAdapter mBTAdapter;

	public BlueReadThread blueConnectThread;

	public int blueConnCount = 0;

	public void closeBluetooth() {
		if (mBTAdapter != null) {
			if (mBTAdapter.isEnabled()) {
				if (blueConnectThread != null) {
					blueConnectThread.cancelDialog();
					blueConnectThread.clearBlueDevices();
					blueConnectThread = null;
				}
				mBTAdapter.cancelDiscovery();
			}
		}
	}

	public GetTableParcel queryDestination(String codeName) {

		SelectTableManager selectTable = new SelectTableManager(this);
		SelectTableParcel entity = new SelectTableParcel();
		entity.setSelectSql(SqlSelectTableManager.SQL_REGION_INFO_ONLY);
		entity.setSelectField(new String[] { codeName });
		entity.setSelectCode(RegionInfoConstant.CODE);
		entity.setSelectName(RegionInfoConstant.NAME);
		entity.setProperty(null);

		GetTableParcel tableData = selectTable.queryOnly(entity);

		return tableData;
	}

	public GetTableParcel queryRecvPerson(String codeName) {

		SelectTableManager selectTable = new SelectTableManager(this);
		SelectTableParcel entity = new SelectTableParcel();
		entity.setSelectSql(SqlSelectTableManager.SQL_STAFF_ONLY);
		entity.setSelectField(new String[] { codeName });

		entity.setSelectCode(SALES_NUMBER);
		entity.setSelectName(SALES_NAME);
		entity.setProperty(null);

		GetTableParcel tableData = selectTable.queryOnly(entity);

		return tableData;
	}

	public GetTableParcel queryNextStation(String codeName) {
		SelectTableManager selectTable = new SelectTableManager(this);
		SelectTableParcel entity = new SelectTableParcel();
		entity.setSelectSql(SqlSelectTableManager.SQL_NEXT_NETSITE_ONLY);
		entity.setSelectField(new String[] { codeName });

		entity.setSelectCode(SITE_CODE_NUMBER);
		entity.setSelectName(SITE_CODE_NAME);
		entity.setProperty(null);

		GetTableParcel tableData = selectTable.queryOnly(entity);

		return tableData;
	}

	public GetTableParcel queryPrevStation(String codeName) {
		SelectTableManager selectTable = new SelectTableManager(this);
		SelectTableParcel entity = new SelectTableParcel();
		entity.setSelectSql(SqlSelectTableManager.SQL_NETSITE_ONLY);
		entity.setSelectField(new String[] { codeName });

		entity.setSelectCode(SITE_CODE_NUMBER);
		entity.setSelectName(SITE_CODE_NAME);
		entity.setProperty(null);

		GetTableParcel tableData = selectTable.queryOnly(entity);

		return tableData;
	}

	public GetTableParcel queryNextDept(String codeName) {
		SelectTableManager selectTable = new SelectTableManager(this);
		SelectTableParcel entity = new SelectTableParcel();
		entity.setSelectSql(SqlSelectTableManager.SQL_NETSITE_NEXT_DEPT_ONLY_LIKE);
		entity.setSelectField(new String[] { codeName });

		entity.setSelectCode(SITE_CODE_NUMBER);
		entity.setSelectName(SITE_CODE_NAME);
		entity.setProperty(null);

		GetTableParcel tableData = selectTable.queryOnly(entity);

		return tableData;
	}

	@Override
	protected void onDestroy() {
		closeBluetooth();
		if (list != null) {
			list.clear();
			list = null;
		}
		if (codes != null) {
			codes.clear();
		}
		super.onDestroy();
	}

	@Override
	public void onScanResults(String str) {
		if (str != null)
			str = str.trim();
		this.str = str;
		handler.post(runnable);
	}

	@Override
	public void onScanResults(String arg0, int arg1) {

	}

	protected abstract void handlerScanData(String scanData);

	protected String getExpType(String code) {
		return ScanRuleManager.getInstance(this).changeCodeType(code);
	}

	protected float parseFloat(String weight) {
		float blueWeight = 0.0f;
		try {
			blueWeight = Float.parseFloat(weight);
		} catch (NumberFormatException e) {
			e.printStackTrace();
		}
		return blueWeight;
	}

	/**
	 * 显示过滤对话框
	 * @param billNo
     */
	public void showFilterDialog(String billNo){
		Helper.showFilterSoundToast(this,
				getString(R.string.code_filter));
		ScanOff();
		final BaseDialog filterDialog=new BaseDialog(this);
		filterDialog.setTitles("此单号【" + billNo + "】为拦截单号，请退回！");
		filterDialog.show();
		filterDialog.getvCanncel().setVisibility(View.GONE);
		filterDialog.getvAccept().setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				filterDialog.dismiss();
				ScanOpen();
			}
		});
	}

	/**
	 * 显示管控对话框
	 * @param billNo
	 */
	public void showControlsDialog(String billNo){
		ScanOff();
		final BaseDialog filterDialog=new BaseDialog(this);
		filterDialog.setTitles("此单号【" + billNo + "】为管控范围外单号，请退回！");
		filterDialog.show();
		filterDialog.getvCanncel().setVisibility(View.GONE);
		filterDialog.getvAccept().setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				filterDialog.dismiss();
				ScanOpen();
			}
		});
	}

	BaseDialog filterDialog=null;
	/**
	 * 显示过滤对话框
	 * @param
	 */
	public void showBlueWeightDialog(float maxValue ,float nowValue){
		ScanOff();
		if(null!=filterDialog)
			filterDialog.dismiss();
		filterDialog=new BaseDialog(this);
		filterDialog.setTitles("重量限制为【" + maxValue + "】。\n当前重量为【" + nowValue + "】！\n请确认重量视为准");
		filterDialog.show();
		filterDialog.getvCanncel().setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				filterDialog.dismiss();
				ScanOpen();
			}
		});
		filterDialog.getvAccept().setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				filterDialog.dismiss();
				ScanOpen();
				return;
			}
		});
	}
}
